const {readJson,writeJson} = require('../../until/fs');
const {STORE_ORDER,STORE_JSON} = require('../../config/config.data');
const moment = require('moment')

// 订单列表获取
let getOrder = (req,res) =>{

    const {shopID,status,pageKey}  = req.body;

    let   orderList = readJson(STORE_ORDER);
          orderList = orderList.filter(item=>item.shopID === shopID)

          //筛选 筛选是已经预约 或者已经取消
          orderList = orderList.filter(item=>item.status === status )   
    let allPageKey = Math.ceil(orderList.lenght/5);
          //做一个过期的判断（亮点）

    // 分页请求 有数量限制
    let startPage = (pageKey-1)*5;
    let endPage   = (pageKey-1)*5+5;
        endPage   = endPage>orderList.length?orderList.length:endPage;

    orderList = orderList.splice(startPage,endPage)
    res.send({code:1,msg:'成功',data:{data:orderList,allPageKey}})
}

// 设置订单已完成

let setOrderStatus =(req,res)=>{

    const {orderid}  = req.body;
    // 读取订单数据
    let orderList = readJson(STORE_ORDER);
    // 锁定需要修改状态的订单
    let index = orderList.findIndex(item=>item.orderid === orderid);

    if(index >-1){

        // 找到，修改状态为完成
        orderList[index].status = 'done';
        // 修改json
        writeJson(STORE_ORDER,orderList);
      
        res.send({code:1,msg:'成功'})
        return 
    }

    res.send({code:0,msg:'失败'})
}

//获取门店信息

let getStoreMessage = (req,res) =>{
    const {shopID}  = req.body;

    // 根据shopID筛出门店信息
    const shopJson = readJson(STORE_JSON);
    let shopItem   = shopJson.find(item=>item.shopID === shopID);
    const {shopName,star,address,longitude,latitude} = shopItem

    //筛选订单列表中当前门店的所有订单   
    let orderList = readJson(STORE_ORDER);
    // 获取所有该商铺的数据
          orderList = orderList.filter(item=>item.shopID === shopID);

    // 获取所有该商铺今天的的数据
    let todayList = orderList.filter(item=>item.createTime >= moment().startOf('day').valueOf() )

    let resData = {
            shopMes:{
                shopName,
                star,
                address,
                longitude,
                latitude
            },
            all:getComputedNum(orderList),
            today:getComputedNum(todayList)
        }

    res.send({code:1,msg:'成功',data:resData})

}

// 计算对应需要的数据
let getComputedNum = arr =>{
    return {
        allNum:arr.length,
        Num:eval(arr.map(item=>item.num*1).join('+'))||0,
        cancelNum:arr.filter(item=>item.status === 'cancel').length
    }
}


module.exports = {getOrder,setOrderStatus,getStoreMessage}